import os
import pyJianYingDraft as draft
from pyJianYingDraft import Intro_type, Transition_type, trange
from datetime import datetime
import shutil

import random
K_ROOT_PATH = r"C:\Users\62524\AppData\Local\JianyingPro\User Data\Cloud files\HBT混剪素材"
k_DRAFT_ROOT=r"D:\app\JianyingPro Drafts"
K_KOUBO_AUDIO_ROOT = os.path.join('.','koubo_audio')

def get_all_files(directory):
    # 获取指定目录下的所有文件
    files = []
    for root, dirs, filenames in os.walk(directory):
        for filename in filenames:
            files.append(os.path.join(root, filename))
    return files

def heqingling_video():
    k_koubo_start = 2000000


    script = draft.Script_file(1080, 1920)
    track_v_main_name = 'main_video_track'
    track_a_bgm_name = "bgm_track"
    track_a_koubo_name = 'koubo_track'
    track_pic_shengliu_name = 'shengliu_track'
    script.add_track(draft.Track_type.video, track_v_main_name)
    script.add_track(draft.Track_type.audio, track_a_bgm_name)
    script.add_track(draft.Track_type.audio, track_a_koubo_name)
    script.add_track(draft.Track_type.video, track_pic_shengliu_name)

    # 获取目标口播音频
    kouboAudioList = get_all_files(K_KOUBO_AUDIO_ROOT)
    if len(kouboAudioList) != 1:
        print(f'口播音频文件有误，找到{len(kouboAudioList)}个')
        return
    kouboAudioPath = kouboAudioList[0]
    koubo_mat = draft.Audio_material(kouboAudioPath)
    script.add_material(koubo_mat)
    koubo_seg = draft.Audio_segment(koubo_mat,trange(k_koubo_start,koubo_mat.duration))
    
    # 获取目标文件
    renWuList = get_all_files(os.path.join(K_ROOT_PATH,'人物'))
    xiaoyuanList = get_all_files(os.path.join(K_ROOT_PATH,'校园'))
    xuexiList = get_all_files(os.path.join(K_ROOT_PATH,'学习'))
    qitaList = get_all_files(os.path.join(K_ROOT_PATH,'其他'))
    

    startVideoPath = os.path.join(K_ROOT_PATH,'片头','港大片头1.mp4')
    video_start_mat = draft.Video_material(startVideoPath)
    script.add_material(video_start_mat)
    video_start_seg = draft.Video_segment(video_start_mat,trange(0,video_start_mat.duration))
    script.add_segment(video_start_seg, track_v_main_name)

    allVideoList = []
    allVideoDuration = video_start_mat.duration

    limitDuration = (k_koubo_start + koubo_mat.duration)
    isStop = False
    while isStop == False:
        # 人物一个
        if len(renWuList) > 0:
            pIndex = random.randint(0,len(renWuList)-1)
            p = renWuList[pIndex]
            v = draft.Video_material(p)
            allVideoDuration += v.duration
            allVideoList.append(v)
            renWuList.remove(p)

        if allVideoDuration >= limitDuration:
            isStop = True
            break

        # 其他随机1~3个
        maxQita = random.randint(1,3)
        for i in range(maxQita):
            if len(qitaList) > 0:
                pIndex = random.randint(0,len(qitaList)-1)
                p = qitaList[pIndex]
                v = draft.Video_material(p)
                allVideoDuration += v.duration
                allVideoList.append(v)
                qitaList.remove(p)
            if allVideoDuration >= limitDuration:
                isStop = True
                break

        if allVideoDuration >= limitDuration:
            isStop = True
            break

        # 学习
        if len(xuexiList) > 0:
            pIndex = random.randint(0,len(xuexiList)-1)
            p = xuexiList[pIndex]
            v = draft.Video_material(p)
            allVideoDuration += v.duration
            allVideoList.append(v)
            xuexiList.remove(p)

        if allVideoDuration >= limitDuration:
            isStop = True
            break

        # 其他随机1~3个
        maxQita = random.randint(1,3)
        for i in range(maxQita):
            if len(qitaList) > 0:
                pIndex = random.randint(0,len(qitaList)-1)
                p = qitaList[pIndex]
                v = draft.Video_material(p)
                allVideoDuration += v.duration
                allVideoList.append(v)
                qitaList.remove(p)
            if allVideoDuration >= limitDuration:
                isStop = True
                break

        if allVideoDuration >= limitDuration:
            isStop = True
            break

        # 校园
        if len(xiaoyuanList) > 0:
            pIndex = random.randint(0,len(xiaoyuanList)-1)
            p = xiaoyuanList[pIndex]
            v = draft.Video_material(p)
            allVideoDuration += v.duration
            allVideoList.append(v)
            xiaoyuanList.remove(p)

        if allVideoDuration >= limitDuration:
            isStop = True
            break
        pass
    
    lastSeg = video_start_seg
    for mat in allVideoList:
        script.add_material(mat)
        seg = None
        if lastSeg.end + mat.duration < limitDuration:
            seg = draft.Video_segment(mat,trange(lastSeg.end,mat.duration))
        else:
            seg = draft.Video_segment(mat,trange(lastSeg.end,limitDuration-lastSeg.end))
        script.add_segment(seg, track_v_main_name)
        lastSeg = seg
    
    script.add_segment(koubo_seg,track_a_koubo_name)

    # 音乐bgm
    bgmAudioPath = os.path.join(K_ROOT_PATH,'音频','是你.wav')
    isEnd = False
    last_bgm_seg = None
    while isEnd == False:
        bgm_mat = draft.Audio_material(bgmAudioPath)
        script.add_material(bgm_mat)
        start = 0
        if last_bgm_seg is not None:
            start = last_bgm_seg.end
        bgm_seg = None
        if start + bgm_mat.duration < limitDuration:
            bgm_seg = draft.Audio_segment(bgm_mat,trange(start,bgm_mat.duration))
        else:
            bgm_seg = draft.Audio_segment(bgm_mat,trange(start,limitDuration-start))
            isEnd = True
        script.add_segment(bgm_seg,track_a_bgm_name)
        last_bgm_seg = bgm_seg
        
    
    #贴纸
    shengliuPath = os.path.join(K_ROOT_PATH,'贴纸','省流文字版贴纸.png')
    shengli_mat = draft.Video_material(shengliuPath)
    script.add_material(shengli_mat)
    shengliu_seg = draft.Video_segment(shengli_mat,trange(0,limitDuration))
    script.add_segment(shengliu_seg,track_pic_shengliu_name)


    now = datetime.now()
    timestamp = now.timestamp()
    filePath = os.path.join(k_DRAFT_ROOT,f"{timestamp}")
    os.makedirs(filePath)
    
    draft_content = os.path.join(filePath,"draft_content.json")
    source_draft_meta = os.path.join('.','template','draft_meta_info.json')
    target_draft_meta = os.path.join(filePath,'draft_meta_info.json')
    script.dump(draft_content)
    shutil.copyfile(source_draft_meta,target_draft_meta)
    print('自动生成结束')
    pass

heqingling_video()